#include <iostream>
#include <string>
#include <pcl/io/ply_io.h>  
#include <pcl/io/pcd_io.h>
#include <pcl/io/vtk_lib_io.h> 
#include <pcl/registration/ndt.h> 
#include <pcl/point_types.h> 
#include <pcl/registration/icp.h> 
#include <pcl/visualization/pcl_visualizer.h> 
#include <pcl/console/time.h>   
#include <pcl/filters/voxel_grid.h> 
#include <pcl/common/transforms.h> 
#include <pcl/io/vtk_lib_io.h> 
#include <vector>
#include <pcl/point_cloud.h>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <pcl/keypoints/sift_keypoint.h>
#include <math.h>

using namespace std;

typedef pcl::PointXYZ PointT;
typedef pcl::PointCloud<PointT> PointCloudT;


bool get_cloud(const string filename, PointCloudT::Ptr points_cloud) {
	pcl::PolygonMesh mesh;
	if (!pcl::io::loadPolygonFile(filename, mesh)) {
		return false;
	}
	fromPCLPointCloud2(mesh.cloud, *points_cloud);
	return true;
}

bool save_txt(const string& filename, PointCloudT::Ptr points_cloud) {
	ofstream ofs;
	ofs.open(filename);
	ofs.setf(ios::fixed, ios::floatfield);  // �趨Ϊ fixed ģʽ����С�����ʾ������
	ofs.precision(4);  // ���þ���
	if (!ofs.is_open() || ofs.fail())
	{
		ofs.close();
		return (false);
	}
	for (auto point : *points_cloud) {
		ofs << point.x << " " << point.y << " " << point.z << endl;
	}
	return true;
}

int main(int argc, char* argv[]) {
	//stl  -->   txt
	//
	if (argc < 2)
	{
		printf("{\"success\":False}");
		return (0);
	}

	PointCloudT::Ptr cloud_in(new PointCloudT);//��ʼ����
	PointCloudT::Ptr cloud_in_filter(new PointCloudT);//�²�������
	pcl::VoxelGrid<pcl::PointXYZ> filter;

	


	float fsize = atof(argv[1]);
	filter.setLeafSize(fsize,fsize,fsize);
	string filename;
    vector<string> Files;
	for (int i = 2; i < argc; ++i) {
		filename = argv[i];
		if (!get_cloud(filename, cloud_in)) {
			printf("{\"success\":False}");
			return (0);
		}

		filename = filename.substr(0,filename.length()-4) + "_sample.txt";
		if (fsize!=0){
			filter.setInputCloud(cloud_in);
			filter.filter(*cloud_in_filter);
			if (!save_txt(filename, cloud_in_filter)) {
				printf("{\"success\":False}");
				return (0);
			}
		}
		else{
			if (!save_txt(filename, cloud_in)) {
				printf("{\"success\":False}");
				return (0);
			}
		}

        Files.push_back(filename);
	}
    printf("{");
	printf("\"success\":true");
    printf(",\"filenames\":[");
    bool isout = false;
    for (auto v:Files){
        if (!isout){
            isout = true;
            printf("\"%s\"",v.c_str());
        }
        else{
            printf(",\"%s\"",v.c_str());
        }
    }
    printf("]");
    printf("}\n");
	return (0);
}